<template>
  <div class="reset-info">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">访客信息登记</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        label-position="left"
        class="visitor-form"
      >
        <el-form-item label="来访人员类别" prop="RYLXMC">
          <el-select
            v-model="formData.RYLXMC"
            placeholder="请选择人员类别"
            style="width: 100%"
            @change="handleVisitorTypeChange"
          >
            <el-option label="施工人员" value="施工人员" />
            <el-option label="其他人员" value="其他人员" />
          </el-select>
        </el-form-item>

        <el-form-item label="企业联系人">
          <el-input
            v-model="formData.QYLXR"
            placeholder="请输入企业联系人"
            clearable
          />
        </el-form-item>

        <el-form-item label="企业名称" prop="LFRGSMC">
          <el-input
            v-model="formData.LFRGSMC"
            placeholder="请输入企业名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="来访人员姓名" prop="XM">
          <el-input v-model="formData.XM" placeholder="请输入姓名" clearable />
        </el-form-item>

        <el-form-item label="联系电话" prop="LXDH">
          <el-input
            v-model="formData.LXDH"
            placeholder="请输入手机号码"
            clearable
          />
        </el-form-item>

        <el-form-item label="来访人数" prop="RS">
          <el-input-number
            v-model="formData.RS"
            :min="1"
            :max="100"
            placeholder="请输入来访人数"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 施工人员专属字段 -->
        <template v-if="formData.RYLXMC === '施工人员'">
          <el-form-item label="预计施工开始时间" prop="YJSGKSSJ">
            <el-date-picker
              v-model="formData.YJSGKSSJ"
              type="date"
              placeholder="选择开始日期"
              style="width: 100%"
              :disabled-date="disabledStartDate"
            />
          </el-form-item>

          <el-form-item label="预计施工结束时间" prop="YJSGJSSJ">
            <el-date-picker
              v-model="formData.YJSGJSSJ"
              type="date"
              placeholder="选择结束日期"
              style="width: 100%"
              :disabled-date="disabledEndDate"
            />
            <div class="tip-text">
              <el-icon><InfoFilled /></el-icon>
              施工时间周期单次填写不允许超过10天
            </div>
          </el-form-item>
        </template>

        <el-form-item label="进场事由" prop="JCSY">
          <el-input
            v-model="formData.JCSY"
            placeholder="请填写进场事由"
            clearable
          />
        </el-form-item>

        <el-form-item label="访问公司名称" prop="QYMC">
          <el-select
            v-model="formData.QYMC"
            placeholder="请选择访问公司"
            style="width: 100%"
          >
            <el-option
              v-for="company in companyList"
              :key="company.QYBH"
              :label="company.QYMC"
              :value="company.QYMC"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
            type="primary"
            @click="handleSave"
            :loading="loading"
            size="large"
          >
            {{ loading ? "保存中..." : "保存" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { InfoFilled } from "@element-plus/icons-vue";
import { saveApi } from "~/composables/useOutsourceOperation";
import type { SaveVisitorParams } from "~/types/api";

interface Props {
  qrObject?: {
    QYMC?: string;
    QYBH?: string;
  };
  WXID?: string;
  data?: any;
  type?: string;
  companyList?: Array<{ QYBH: string; QYMC: string }>;
}

const props = withDefaults(defineProps<Props>(), {
  qrObject: () => ({}),
  data: () => ({}),
  type: "qy",
  companyList: () => [],
});

const emit = defineEmits<{
  getDetail: [];
}>();

const formRef = ref<FormInstance>();
const loading = ref(false);

const formData = ref({
  QYMC: "",
  XM: "",
  LXDH: "",
  RS: 1,
  QYLXR: "",
  LFRGSMC: "",
  RYLXMC: "",
  JCSY: "",
  YJSGKSSJ: "",
  YJSGJSSJ: "",
});

const formRules: FormRules = {
  RYLXMC: [
    { required: true, message: "请选择来访人员类别", trigger: "change" },
  ],
  LFRGSMC: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  XM: [{ required: true, message: "请输入来访人员姓名", trigger: "blur" }],
  LXDH: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  RS: [
    { required: true, message: "请输入来访人数", trigger: "blur" },
    { type: "number", min: 1, message: "人数必须大于0", trigger: "blur" },
  ],
  JCSY: [{ required: true, message: "请输入进场事由", trigger: "blur" }],
  QYMC: [{ required: true, message: "请选择访问公司名称", trigger: "change" }],
  YJSGKSSJ: [
    { required: true, message: "请选择施工开始时间", trigger: "change" },
  ],
  YJSGJSSJ: [
    { required: true, message: "请选择施工结束时间", trigger: "change" },
  ],
};

const handleVisitorTypeChange = (value: string) => {
  if (value !== "施工人员") {
    formData.value.YJSGKSSJ = "";
    formData.value.YJSGJSSJ = "";
  }
};

const disabledStartDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7; // 不能选择今天之前的日期
};

const disabledEndDate = (time: Date) => {
  if (!formData.value.YJSGKSSJ) return time.getTime() < Date.now() - 8.64e7;
  const startDate = new Date(formData.value.YJSGKSSJ);
  const maxDate = new Date(startDate);
  maxDate.setDate(startDate.getDate() + 10);
  return (
    time.getTime() < startDate.getTime() || time.getTime() > maxDate.getTime()
  );
};

const validateForm = async (): Promise<boolean> => {
  if (!formRef.value) return false;

  try {
    await formRef.value.validate();

    // 额外的施工人员验证
    if (formData.value.RYLXMC === "施工人员") {
      const start = new Date(formData.value.YJSGKSSJ);
      const end = new Date(formData.value.YJSGJSSJ);
      const diffDays = Math.ceil(
        (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
      );

      if (diffDays > 10) {
        ElMessage.error("施工时间周期单次填写不允许超过10天");
        return false;
      }

      if (start > end) {
        ElMessage.error("施工结束时间需大于施工开始时间");
        return false;
      }
    }

    return true;
  } catch {
    return false;
  }
};

const handleSave = async () => {
  if (!(await validateForm())) {
    return;
  }

  loading.value = true;

  try {
    const params: SaveVisitorParams = {
      RYLX: {
        ID: formData.value.RYLXMC === "施工人员" ? "1" : "99",
        VALUE: formData.value.RYLXMC === "施工人员" ? "施工" : "其他",
      },
      LFRGSMC: formData.value.LFRGSMC,
      XM: formData.value.XM,
      LXDH: formData.value.LXDH,
      RS: formData.value.RS.toString(),
      JCSY: formData.value.JCSY,
      QYMC: formData.value.QYMC,
      QYBH: props.qrObject?.QYBH || "",
      WXID: props.WXID,
      ...(formData.value.RYLXMC === "施工人员" && {
        SGLX: "施工",
        YJSGKSSJ: formData.value.YJSGKSSJ,
        YJSGJSSJ: formData.value.YJSGJSSJ,
      }),
    };

    const response = await saveApi(params);

    if (response.code === "-1") {
      ElMessage.error(response.message || "保存失败");
      return;
    }

    ElMessage.success("保存成功");
    emit("getDetail");
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 监听props数据变化
watch(
  () => props.data,
  (newData) => {
    if (newData) {
      formData.value = {
        ...formData.value,
        ...newData,
        RYLXMC: newData.RYLXVALUE || "",
        QYMC: newData.QYMC || "",
      };
    }
  },
  { immediate: true, deep: true }
);

// 设置默认公司
watch(
  () => props.qrObject,
  (newQrObject) => {
    if (newQrObject?.QYMC && !formData.value.QYMC) {
      formData.value.QYMC = newQrObject.QYMC;
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.reset-info {
  padding: 20px;
}

.form-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #303133;
}

.visitor-form {
  padding: 1rem 0;
}

.tip-text {
  margin-top: 8px;
  font-size: 0.8rem;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.form-actions {
  margin-top: 2rem;
  text-align: center;
}

.form-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reset-info {
    padding: 15px;
  }

  .form-card {
    margin: 0;
  }
}
</style>
